import pyshark
import csv

output_file = 'ftp_login_logs.csv'

capture = pyshark.FileCapture('ftp_traffic.pcap')

with open(output_file, 'w', newline='') as csvfile:
    csvwriter = csv.writer(csvfile)
    # 表头
    csvwriter.writerow(['时间', '源 MAC', '源 IP', '目标 MAC', '目标 IP', '登录名', '口令', '成功与否'])

    # 初始化用户名和密码
    username = None
    password = None

    # 遍历每个数据包
    for packet in capture:
        try:
            # 提取报文中的时间戳、源 MAC、源 IP、目标 MAC、目标 IP
            timestamp = packet.sniff_time.strftime('%Y-%m-%d %H:%M:%S')
            src_mac = packet.eth.src
            src_ip = packet.ip.src
            dst_mac = packet.eth.dst
            dst_ip = packet.ip.dst

            # 判断是否是FTP请求，并提取用户名和密码
            if hasattr(packet.ftp, 'request_command'):
                if packet.ftp.request_command == 'USER':
                    username = packet.ftp.request_arg
                elif packet.ftp.request_command == 'PASS':
                    password = packet.ftp.request_arg

            # 判断是否是登录成功或失败的响应
            if hasattr(packet.ftp, 'response_code'):
                if packet.ftp.response_code == '230':
                    login_status = 'SUCCEED'
                    # 用户名和密码都已经提取到
                    if username and password:
                        csvwriter.writerow(
                            [timestamp, src_mac, src_ip, dst_mac, dst_ip, username, password, login_status])
                        # 重置用户名和密码
                        username = None
                        password = None
                elif packet.ftp.response_code == '530':
                    login_status = 'FAILED'
                    if username and password:
                        csvwriter.writerow(
                            [timestamp, src_mac, src_ip, dst_mac, dst_ip, username, password, login_status])
                        # 重置用户名和密码
                        username = None
                        password = None
        except AttributeError:
            continue
